package com._58city.spark.app.redis;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

import com.google.common.base.Objects;

/**
 * @author lihao
 * 将维度值转化为对象属性的工具类
 */
public class TransferDimensionUtil {
	
	/**
	 * 该方法主要通过反射的方式赋值到对象属性
	 * @param model
	 * @param keys
	 * @param values
	 */
	public static void dimension(Object model, String[] keys, Object... values){
		if(values.length != keys.length) 
			throw new IllegalArgumentException("transfer param is error!");
		try {
			Class<?> clazz = model.getClass();
		    PropertyDescriptor[] props = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
			for(int i = 0; i<keys.length; i++){
				String key = keys[i]; 
				key = key.substring(2, key.length() - 1).trim();
				for(PropertyDescriptor prop : props){
		        	String fieldName = prop.getName();
		        	if(!"class".equals(fieldName)){
		        		if(fieldName.equals(key)){
		        			Method method = prop.getWriteMethod();
		        			method.invoke(model, values[i]);
		        		}
		        	}
		        }
			}
		} catch (Exception e) {
			throw new IllegalStateException("transfer is error!",e);
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TrackModel model = new TrackModel();
		String[] keys = new String[]{"${platform}","${busiLine}"};
		String keystr = "-1,zhaopin";
		String[] key = keystr.split(",");
		TransferDimensionUtil.dimension(model, keys, Integer.parseInt(key[0]),key[1]);
		System.out.println(model.toString());
		
		
//		CpcModel model = new CpcModel();
//		String[] keys = new String[]{"${platform}","${busiLine}"};
//		String keystr = "1426145200000,2,zhaopin";
//		String[] key = keystr.split(",");
//		model.setTime(Long.parseLong(key[0]));
//		
//        TransferDimensionUtil.dimension(model, keys, Integer.parseInt(key[1]),key[2]);
//        model.setValue(1);
//        System.out.println(model.toString());
	}

}
